<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ChargeOrder
 *
 * @author sunday add 2014.5.28
 */
//require_once CONFIGPATH.'inc.php';
class ChargeOrder {

    private $db;

    function __construct() {
        require (CONFIGPATH . 'db.php');
        $this->db = new Database($config['payment_db']);
    }

    /*
     * $status: 0等待支付，1表示成功，2表示失败，3已发放  4表示补单成功
     * $money: 人民币
     * $orderid:我方订单号
     * $chennelid:渠道
     * $platfrom：平台
     * $thirdorderid:第三方平台订单号
     */
    function recordOrder($status, $money, $orderid, $channelid, $platform,$thirdorderid='') {
        
        $sql = "SELECT * FROM {pre}payment WHERE orderid='{$orderid}'AND channel='{$channelid}' AND platform='{$platform}'";
        $row = $this->db->one($sql);
        if ($row != null) {
            //如果为已经记录下的订单
            if ($row['status'] != STATUS_WAIT_CHARGE) {
                return TRUE;
            }
        } else {
            //echo " ChargeOrder: can not find order {$orderid} channel {$channelid} platform {$platform} \r\n";
            $this->log("error", "ChargeOrder: can not find order {$orderid} channel {$channelid} platform {$platform} \r\n");
            return FALSE;
        }

        //更新订单信息
        $now = date("Y-m-d H:i:s", time());
        $jsonStr = json_encode($_REQUEST);
        //$row['content'] = $jsonStr;
        //$row['finish_time'] = $now;
        //$row['status'] = $status;
        //$row['money'] = $money;
        //插入到有效订单的表中
        //$res = $this->db->insert("{pre}payment",$row);
        
        
        $sql = "UPDATE {pre}payment SET `status`='{$status}',`finish_time`='{$now}',`content`='{$jsonStr}',`money`='{$money}',`thirdorderid`='{$thirdorderid}' WHERE orderid='{$orderid}' AND channel='{$row['channel']}' AND platform='{$row['platform']}' ";
        $res = $this->db->execute($sql);

        //第几次充值
        $paytimes = 0;
        $sql = "SELECT * FROM {pre}payment WHERE serverid = ".$row['serverid']." AND roleid='".$row['roleid']."'";
        $this->db->query($sql);
        $rolepayarr = array();
        while ($n = $this->db->get_array())
        {
        	$rolepayarr[] = $n;
        }
        for ($i = 0; $i < count($rolepayarr); $i++)
        {
        	if (isset($rolepayarr[$i]['money']))
        	{
        		$paytimes += 1;
        	}
        }
        
        //订单信息更新成功 开始发放充值
        if ($res !== FALSE && ($status == STATUS_SUCCESS  || $status == 4)) {  //4表示补单的情况
            $serverInfo = $this->db->one("SELECT * FROM {pre}areasample WHERE `id`='" . $row['serverid'] . "'");
            $one['orderid'] = (string) $row['orderid'];
            $one['roleid'] = (int) $row['roleid'];
            $one['channel'] = (string) $row['channel'];
            $one['money'] = (string) $money;
            $one['platform'] = (int) $row['platform'];
            $one['finish_time'] = (string) $now;
            $one['product_id'] = (int)$row['product_id'];
            $one['paytimes'] = $paytimes;  //累计支付次数
            $datas[] = $one;
            $json_str = json_encode($datas);
            $json_str = str_replace(" ", "%20", $json_str);

            $strResult = vpost($serverInfo['host'] . "json_str=$json_str&action=45", 10);     //请求游戏服务器发放充值
            //推送游戏服务器超时或者失败
            if ($strResult === FALSE || $strResult=="fail") {
                echo "error:area sending fail ";
                //插入临时表格
                unset($row['send_time']);
                unset($row['id']);
                $res = $this->db->insert("{pre}payment_tmp", $row, true);
                if ($res == FALSE)
                    $this->log("error", "{$orderid} orderid insert into tmp_table error;");
            }
        }
        else {
            //$this->log("error", "{$orderid} not STATUS_SUCCESS, something error");
            echo " ChargeOrder: {$orderid} not STATUS_SUCCESS, something error \r\n";
            return FALSE;
        }
        return TRUE;
    }

    function log($folderName, $data) {
        if (is_array($data)) {
            $log = date("Y-m-d H:i:s") . " " . http_build_query($data) . "\r\n";
        } else {
            $log = date("Y-m-d H:i:s") . " " . $data . "\r\n";
        }
        $path = APPPATH . "channels/log/{$folderName}/";
        createDir($path);
        $path = $path . date("Y-m-d") . ".txt";
        file_put_contents($path, $log, FILE_APPEND);
    }

}
